#include <iostream>
#include <string>
#include <vector>
#include <sqlite3.h>
#include <libsqlitewrapped.h>
#include <cstdlib>
#include "Event.h"
using namespace std;

//CREATE TABLE events (id INTEGER PRIMARY KEY, date, time, name, class, details, priority, actually_worth_doing);
Event::Event(Database* dbinit, int getid) {
	db = dbinit;
	Query q(*db);
	if (!getid) {
		q.execute("INSERT INTO events VALUES (NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL)");
		id = q.insert_id();
	} else {
		id = getid;
	}
	char var[100];
	sprintf(var, "SELECT * FROM events WHERE id=%d", id);
	q.get_result(var);
	while (q.fetch_row()) {
		id = q.getval();
		date = q.getstr();
		time = q.getstr();
		name = q.getstr();
		class_name = q.getstr();
		details = q.getstr();
		priority = q.getval();
		actually_worth_doing = q.getval();
	}
}

void Event::update() {
	Query q(*db);
	char updatestring[1000];
	sprintf(updatestring, 
	"UPDATE events SET date=\"%s\", time=\"%s\", name=\"%s\", class=\"%s\", details=\"%s\",  priority=%d, actually_worth_doing=%d WHERE id=%d", 
	date.c_str(), time.c_str(), name.c_str(), class_name.c_str(), details.c_str(), priority, actually_worth_doing, id);
	q.execute(updatestring);
}

void Event::remove() {
	Query q(*db);
	char updatestring[100];
	sprintf(updatestring, "DELETE FROM events WHERE id=%d", id);
	q.execute(updatestring);
}

vector<Event*> Event::get_all_events(Database* dbtmp) {
	Query q(*dbtmp);
	int idtmp;
	Event* eventptr;
	vector<Event*> eventptrvec;
	
	q.get_result("SELECT * FROM events");

	while (q.fetch_row()) {
		idtmp = q.getval();
		eventptr = new Event(dbtmp, idtmp);
		eventptrvec.push_back(eventptr);
	}
	return eventptrvec;
}
